import Vue from 'vue'
import Router from 'vue-router'
import routes from './routes'
import store from '@/store'
import { getOpenidCookie } from '@/libs/storage'
import { isWechat, wxAuth } from '@/libs/utils'
import { API_FAST_LOGIN } from '@/service/account'

Vue.use(Router)

const router = new Router({
  mode: 'hash',
  routes
})

const wachatBlackList = ['login', 'regist', 'forget']
const loginBlackList = ['login', 'regist', 'forget', 'error', 'certificate']
const notLoginBlackList = ['stadium-comment', 'social-publish', 'voice-form', 'user-home', 'user-info', 'user-orders', 'change-phone', 'user-abou', 'user-order-detail']

router.beforeEach((to, from, next) => {
  if (isWechat()) {
    if (wachatBlackList.indexOf(to.name) !== -1) {
      next({
        name: 'home'
      })
    }
    // 微信登录情况
    // console.log('微信登录情况')
    // console.log('openid', getOpenidCookie())
    if (!getOpenidCookie()) {
      console.info('授权登录，跳转', to.fullPath)
      // setBeforeLoginUrl(to.name)
      // console.info('存储用户进入地址', getBeforeLoginUrl())
      // console.log('跳转前地址', to.fullPath)
      wxAuth(to.fullPath)
      // next()
    } else {
      console.info('openid有效，已登录')
      if (!store.state.account.accessToken || !store.state.user.userInfo) {
        console.info('在这里快速登录')
        API_FAST_LOGIN(getOpenidCookie()).then((resData) => {
          let { access_token, refresh_token, userId, nickname, headImagerUrl, phoneNum } = resData
          store.dispatch('saveToken', { access_token, refresh_token })
          store.dispatch('saveUserInfo', {
            nickname,
            userId,
            phoneNum,
            headImagerUrl
          })
        })
      }
      next()
      // let beforeURL = getBeforeLoginUrl()
      // if (beforeURL) {
      //   removeBeforeLoginUrl()
      //   next({
      //     name: beforeURL
      //   })
      //   console.info('进入之前的地址')
      // } else {
      //   next()
      // }
    }
  } else {
    // 普通登录情况
    // console.log('普通登录情况')
    if (store.state.account.accessToken) {
      loginBlackList.indexOf(to.name) !== -1 ? next({ name: 'home' }) : next()
    } else {
      // 判断login 避免死循环
      if (notLoginBlackList.indexOf(to.name) === -1) {
        next()
      } else {
        next({ name: 'login' })
      }
    }
  }
})

router.beforeResolve((to, from, next) => {
  /* 路由发生变化修改页面title */
  if (to.meta.title) {
    document.title = to.meta.title
  }
  next()
})

router.afterEach((to, from) => {
})

export default router
